﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Diagnostics;

namespace Comport
{
    public class Comport
    {
        private Object BufferInLock = new Object();
        private object BufferOutLock = new Object();
        #region portsettings
        private SerialPort mySerialport = new SerialPort();
        private string port = "COM2";
        private int outValue;
        private int b_outValue;
        private int led;
        ComName.ComName Comname = new ComName.ComName();
        #endregion 
        #region buffer
        public void dataOut(int value)
        {
            lock (BufferOutLock)
            {
                outValue = value;
            }
        }
        public string dataIn()
        {
            lock (BufferInLock)
            {
                try
                {
                    return mySerialport.ReadExisting();
                }
                catch
                {
                    return "";
                }
            }
        }
        #endregion
        public Comport()
        {
            SetPort();

        }
        ~Comport()
        {
            this.disconnect();
        }
        private void SetPort()
        {
            this.disconnect();
            Debug.WriteLine("get port name");
            this.port = Comname.GetPort();
            this.connect();
        }
        public void ThreadSendMain()
        {
            lock (BufferInLock)
            {
                b_outValue = outValue;
            }
            this.connect();
            try
            {
                led = 1;
                this.mySerialport.WriteLine("SS");
                this.mySerialport.WriteLine("V" + b_outValue);
                this.mySerialport.WriteLine("L" + led);
            }
            catch
            {
                Debug.WriteLine("Error: Comp can't send data");
            }
            //
        }

        private void connect()
        {
            try
            {
                if (!mySerialport.IsOpen)
                {
                    mySerialport.PortName = this.port;
                    mySerialport.BaudRate = 9600;
                    mySerialport.Open();
                }
            }
            catch
            {
                Debug.WriteLine("Error: Comp " + this.port + " could not be opend");
                SetPort();
            }
        }
        private void disconnect()
        {
            try
            {
                if (mySerialport.IsOpen)
                {
                    mySerialport.Close();
                }
            }
            catch
            {
                Debug.WriteLine("Error: can't close serial port");
            }
        }
    }
}
